package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProduct;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductVOApi;
import cn.wolfcode.redis.SeckillRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时任务：将mysql秒杀商品+对应的商品详情的数据查询出来，封装到SecKillProductVO中;
 *          保存到redis中。hash结构为 time <seckillId,String类型的SecKillProductVO>
 *
 */
@Component
@RefreshScope
@Slf4j
@Setter
@Getter
public class MyInitSeckillProductCountJob implements SimpleJob {
    //配置执行时间cron
    @Value("${jobCron.initSeckillProductCount}")
    private String cron;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SeckillProductVOApi seckillProductVOApi;
    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println(shardingContext.getShardingParameter());
        //1、查询seckillProduct服务，返回要求的seckillproduct集合
        Result<List<SeckillProduct>> result = seckillProductVOApi.getSeckillProducts(Long.valueOf(shardingContext.getShardingParameter()));
        List<SeckillProduct> seckillProducts=result.getData();
        //2、将数量保存到redis中 ;hash time <seckillid,stockCount>
        for (SeckillProduct seckillProduct:seckillProducts){
            String time=seckillProduct.getTime()+"";
            String seckillId=seckillProduct.getId()+"";
            Integer seckillCount=seckillProduct.getStockCount();
            stringRedisTemplate.opsForHash().
                    put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),seckillId,seckillCount+"");
        }
        
    }
}
